﻿using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.WebControls;
using NotAClue.Web;
using NotAClue.Web.DynamicData;
using NotAClue;

namespace DD_Extensions
{
    public partial class Enumeration_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        private Type _enumType;
        private Type EnumType
        {
            get
            {
                if (_enumType == null)
                    _enumType = Column.GetEnumType();

                return _enumType;
            }
        }

        private Boolean EnumFlags { get; set; }

        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // set field options
            this.SetFieldOptions();

            // add CSS from meta data
            this.ApplyCss();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            EnumFlags = EnumType.GetCustomAttributes(typeof(FlagsAttribute), true).GetLength(0) > 0;

            if (!EnumFlags)
            {
                DropDownList1.ToolTip = Column.Description;

                if (DropDownList1.Items.Count == 0)
                {
                    if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
                        DropDownList1.Items.Add(new ListItem("[Not Set]", String.Empty));

                    EnumWebExtensionMethods.FillEnumListControl(DropDownList1, EnumType);
                }

                SetUpValidator(RequiredFieldValidator1);
                RequiredFieldValidator1.Text = "*";
                SetUpValidator(DynamicValidator1);
                DynamicValidator1.Text = "*";

                // set validators to use image as error indicator
                this.SetValidatorsToImage();
            }
            else
            {
                DropDownList1.Visible = false;
                CheckBoxList1.Visible = true;
                CheckBoxList1.ToolTip = Column.Description;

                if (CheckBoxList1.Items.Count == 0)
                    EnumWebExtensionMethods.FillEnumListControl(CheckBoxList1, EnumType);
            }
        }

        protected void DropDownList1_PreRender(object sender, EventArgs e)
        {
            if (!EnumFlags)
            {
                string value = Request.QueryString[Column.Name];
                if (this.Mode == DataBoundControlMode.Insert && !string.IsNullOrEmpty(value))
                {
                    ListItem item = DropDownList1.Items.FindByValue(value);
                    if (item != null)
                        DropDownList1.SelectedValue = value;
                }
            }

            if (Mode == DataBoundControlMode.Insert)
            {
                var value = this.GetDefaultValue(Column);
                if (!String.IsNullOrEmpty(value))
                {
                    ListItem item = DropDownList1.Items.FindByValue(value);
                    if (item != null)
                        DropDownList1.SelectedValue = item.Value;
                }
            }
        }

        public string EnumFieldValueString
        {
            get
            {
                if (FieldValue == null)
                    return FieldValueString;

                Type enumType = Column.GetEnumType() ?? Column.Attributes.OfType<EnumDataTypeAttribute>().SingleOrDefault().EnumType;

                if (enumType != null)
                {
                    object enumValue = Enum.ToObject(enumType, FieldValue);
                    return FormatFieldValue(enumValue);
                }

                return FieldValueString;
            }
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            if (Mode == DataBoundControlMode.Edit && FieldValue != null)
            {
                if (!EnumFlags)
                {
                    string fieldValue = EnumExtensionMethods.GetUnderlyingTypeValueString(EnumType, FieldValue);
                    ListItem item = DropDownList1.Items.FindByValue(fieldValue);
                    if (item != null)
                        DropDownList1.SelectedValue = fieldValue;
                }
                else
                {
                    var values = EnumFieldValueString.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (ListItem item in CheckBoxList1.Items)
                    {
                        if (values.Contains(item.Text))
                            item.Selected = true;
                        else
                            item.Selected = false;
                    }
                }
            }
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            if (!EnumFlags)
            {
                string value = DropDownList1.SelectedValue;
                if (value == String.Empty)
                    value = null;

                dictionary[Column.Name] = ConvertEditedValue(value);
            }
            else
            {
                int enumValue = 0;
                foreach (ListItem item in CheckBoxList1.Items)
                {
                    if (item.Selected)
                    {
                        var itemValue = int.Parse(item.Value);
                        enumValue = enumValue | itemValue;
                    }
                }
                dictionary[Column.Name] = ConvertEditedValue(enumValue.ToString());
            }
        }

        public override Control DataControl
        {
            get
            {
                if (!EnumFlags)
                    return DropDownList1;
                else
                    return CheckBoxList1;
            }
        }
    }
}